/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "i2c.h"
#include "spi.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "keyDedect.h"
#include "eeprom.h"
#include "spi_flash.h"
#include "light_sensor.h"
#if ENABLE_TFT_DISPLAY
#include "TFTh/TFT_init.h"
#include "TFTh/TFT_CAD.h"
#include "TFTh/TFT_text.h"
#include "TFTh/TFT_io.h"
#endif
#if ENABLE_OLED_DISPLAY
#include "oled/oled.h"  // 添加OLED驱动头文件
#endif
#if ENABLE_MPU6050
#include "mpu6050/mpu6050.h"  // 添加MPU6050头文件
#include "mpu6050/iic.h"     // 添加IIC头文件
#endif
#include "HC_SR04/sr04.h"  // 添加HC-SR04头文件
#include <stdio.h>      // 添加stdio.h用于sprintf函数
#include <math.h>       // 添加math.h用于数学计算
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
#if ENABLE_TFT_DISPLAY
TFT_HandleTypeDef htft;
#endif
sr04_t hc_sr04;  // 添加HC-SR04实例
static uint32_t last_trigger_time = 0;  // 添加触发时间变量

// 光电对管中断相关变量（使用volatile确保中断安全）
volatile uint32_t gou_trigger_count = 0;  // 光电对管触发计数
volatile uint32_t last_gou_time = 0;      // 上次触发时间
volatile uint8_t gou_state_changed = 0;   // 状态变化标志
volatile uint8_t current_gou_state = 0;   // 当前状态
static uint32_t last_debounce_time = 0;   // 防抖时间

// 添加缺少的变量定义
volatile uint32_t light_sensor_count = 0;  // 光传感器计数
volatile uint8_t light_sensor_blocked = 0; // 光传感器阻挡状态
volatile uint8_t tft_update_flag = 0;      // TFT更新标志

#if ENABLE_MPU6050
// MPU6050相关变量
static short mpu_accel_x, mpu_accel_y, mpu_accel_z;  // 加速度计数据
static short mpu_gyro_x, mpu_gyro_y, mpu_gyro_z;     // 陀螺仪数据
static float mpu_temperature;                         // 温度数据
static uint8_t mpu_update_flag = 0;                   // MPU数据更新标志
static uint32_t mpu_last_update = 0;                  // 上次更新时间
#endif

#if ENABLE_LED_TEST
// LED测试相关变量
static uint32_t led_blink_timer = 0;
static uint8_t led_blink_count = 0;
#endif
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */



/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_I2C1_Init();
  MX_SPI2_Init();
  MX_ADC1_Init();
  MX_USART1_UART_Init();
  MX_SPI1_Init();
  MX_TIM1_Init();
  /* USER CODE BEGIN 2 */
  
  // HC-SR04初始化（简化版本）
  hc_sr04.distance = 0;
  hc_sr04.last_distance = 0;
  
#if ENABLE_MPU6050
  // MPU6050初始化
  if(MPU_Init() == 0) {
    // 初始化成功，读取初始数据
    MPU_Get_Accelerometer(&mpu_accel_x, &mpu_accel_y, &mpu_accel_z);
    MPU_Get_Gyroscope(&mpu_gyro_x, &mpu_gyro_y, &mpu_gyro_z);
    mpu_temperature = MPU_Get_Temperature();
    mpu_last_update = HAL_GetTick();
  }
#endif
  
#ifdef ENABLE_TFT_DISPLAY
  // TFT初始化 - 使用正确的引脚定义
  TFT_Init_Instance(&htft, &hspi1, CS_GPIO_Port, CS_Pin); // CS=PC2
  
  // 配置TFT控制引脚 - 使用main.h中定义的实际引脚
  TFT_Config_Pins(&htft, DC_GPIO_Port, DC_Pin, RST_GPIO_Port, RST_Pin, BLK_GPIO_Port, BLK_Pin); // DC=PC1, RES=PC0, BL=PA8
  
  // 初始化ST7735S屏幕
  TFT_Init_ST7735S(&htft);
  
  // 清屏 - 使用填充区域函数
  TFT_Fill_Area(&htft, 0, 0, 128, 160, BLACK);
  
  // 显示标题
  TFT_Show_String(&htft, 5, 5, (const uint8_t*)"MPU6050 Data:", WHITE, BLACK, 12, 0);
  TFT_Show_String(&htft, 5, 20, (const uint8_t*)"Accel X:", GREEN, BLACK, 12, 0);
  TFT_Show_String(&htft, 5, 35, (const uint8_t*)"Accel Y:", GREEN, BLACK, 12, 0);
  TFT_Show_String(&htft, 5, 50, (const uint8_t*)"Accel Z:", GREEN, BLACK, 12, 0);
  TFT_Show_String(&htft, 5, 65, (const uint8_t*)"Gyro X:", BLUE, BLACK, 12, 0);
  TFT_Show_String(&htft, 5, 80, (const uint8_t*)"Gyro Y:", BLUE, BLACK, 12, 0);
  TFT_Show_String(&htft, 5, 95, (const uint8_t*)"Gyro Z:", BLUE, BLACK, 12, 0);
  TFT_Show_String(&htft, 5, 110, (const uint8_t*)"Temp:", RED, BLACK, 12, 0);
  TFT_Show_String(&htft, 5, 125, (const uint8_t*)"Count:", YELLOW, BLACK, 12, 0);
#endif

#if ENABLE_OLED_DISPLAY
  // OLED初始化
  OLED_Init();
  OLED_NewFrame();  // 清空显存，替代OLED_Clear()
  OLED_PrintASCIIString(0, 0, "MPU6050 Data:", &afont16x8, OLED_COLOR_NORMAL);
  OLED_PrintASCIIString(0, 16, "Accel: 0,0,0", &afont16x8, OLED_COLOR_NORMAL);
  OLED_PrintASCIIString(0, 32, "Gyro: 0,0,0", &afont16x8, OLED_COLOR_NORMAL);
  OLED_PrintASCIIString(0, 48, "Temp: 0.0C", &afont16x8, OLED_COLOR_NORMAL);
  OLED_ShowFrame();  // 显示到屏幕
#endif

#if ENABLE_LED_TEST
  // LED初始化为关闭状态
  HAL_GPIO_WritePin(LED1_GPIO_Port, LED1_Pin, GPIO_PIN_RESET);
  
  // 读取光电管初始状态并设置LED
  current_gou_state = HAL_GPIO_ReadPin(GDOH_GPIO_Port, GDOH_Pin);
  if (current_gou_state == GPIO_PIN_SET) {
      HAL_GPIO_WritePin(LED1_GPIO_Port, LED1_Pin, GPIO_PIN_SET);
  } else {
      HAL_GPIO_WritePin(LED1_GPIO_Port, LED1_Pin, GPIO_PIN_RESET);
  }
#endif
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
    
#if ENABLE_MPU6050
    // MPU6050数据更新（每100ms更新一次）
    if (HAL_GetTick() - mpu_last_update >= 100) {
      mpu_last_update = HAL_GetTick();
      
      // 读取MPU6050数据
      if (MPU_Get_Accelerometer(&mpu_accel_x, &mpu_accel_y, &mpu_accel_z) == 0 &&
          MPU_Get_Gyroscope(&mpu_gyro_x, &mpu_gyro_y, &mpu_gyro_z) == 0) {
        mpu_temperature = MPU_Get_Temperature();
        mpu_update_flag = 1;  // 设置更新标志
      }
    }
#endif

#ifdef ENABLE_TFT_DISPLAY
    // 主循环中的TFT更新
    if (tft_update_flag || mpu_update_flag) {
      tft_update_flag = 0;
      
#if ENABLE_MPU6050
      if (mpu_update_flag) {
        mpu_update_flag = 0;
        
        // 更新MPU6050数据显示
        char data_str[20];
        
        // 显示加速度计数据
        sprintf(data_str, "%d", mpu_accel_x);
        TFT_Fill_Area(&htft, 65, 20, 128, 32, BLACK);
        TFT_Show_String(&htft, 65, 20, (const uint8_t*)data_str, GREEN, BLACK, 12, 0);
        
        sprintf(data_str, "%d", mpu_accel_y);
        TFT_Fill_Area(&htft, 65, 35, 128, 47, BLACK);
        TFT_Show_String(&htft, 65, 35, (const uint8_t*)data_str, GREEN, BLACK, 12, 0);
        
        sprintf(data_str, "%d", mpu_accel_z);
        TFT_Fill_Area(&htft, 65, 50, 128, 62, BLACK);
        TFT_Show_String(&htft, 65, 50, (const uint8_t*)data_str, GREEN, BLACK, 12, 0);
        
        // 显示陀螺仪数据
        sprintf(data_str, "%d", mpu_gyro_x);
        TFT_Fill_Area(&htft, 65, 65, 128, 77, BLACK);
        TFT_Show_String(&htft, 65, 65, (const uint8_t*)data_str, BLUE, BLACK, 12, 0);
        
        sprintf(data_str, "%d", mpu_gyro_y);
        TFT_Fill_Area(&htft, 65, 80, 128, 92, BLACK);
        TFT_Show_String(&htft, 65, 80, (const uint8_t*)data_str, BLUE, BLACK, 12, 0);
        
        sprintf(data_str, "%d", mpu_gyro_z);
        TFT_Fill_Area(&htft, 65, 95, 128, 107, BLACK);
        TFT_Show_String(&htft, 65, 95, (const uint8_t*)data_str, BLUE, BLACK, 12, 0);
        
        // 显示温度数据
        sprintf(data_str, "%.1fC", mpu_temperature);
        TFT_Fill_Area(&htft, 45, 110, 128, 122, BLACK);
        TFT_Show_String(&htft, 45, 110, (const uint8_t*)data_str, RED, BLACK, 12, 0);
      }
#endif
      
      // 更新计数显示
      char count_str[20];
      sprintf(count_str, "%lu", gou_trigger_count);
      TFT_Fill_Area(&htft, 50, 125, 128, 137, BLACK);
      TFT_Show_String(&htft, 50, 125, (const uint8_t*)count_str, YELLOW, BLACK, 12, 0);
      
      // 更新状态显示
      const char* status = light_sensor_blocked ? "Blocked" : "Normal";
      uint16_t status_color = light_sensor_blocked ? RED : BLUE;
      TFT_Fill_Area(&htft, 5, 140, 128, 152, BLACK);
      TFT_Show_String(&htft, 5, 140, (const uint8_t*)status, status_color, BLACK, 12, 0);
    }
#endif

#if ENABLE_LED_TEST
    // LED控制由中断处理，主循环中不需要额外处理
    HAL_Delay(10);  // 减少CPU占用
#endif
    
    /* USER CODE END WHILE */
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
  PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV2;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
  if (GPIO_Pin == GDOH_Pin) {
    uint32_t current_time = HAL_GetTick();
    
    // 防抖处理（50ms）
    if (current_time - last_debounce_time > 50) {
      last_debounce_time = current_time;
      
      uint8_t new_state = HAL_GPIO_ReadPin(GDOH_GPIO_Port, GDOH_Pin);
      
      // 检测下降沿（从高到低）
      if (current_gou_state == GPIO_PIN_SET && new_state == GPIO_PIN_RESET) {
        gou_trigger_count++;
        gou_state_changed = 1;
        tft_update_flag = 1;  // 添加TFT更新标志
      }
      
      current_gou_state = new_state;
      light_sensor_blocked = (new_state == GPIO_PIN_RESET) ? 1 : 0;
      
#if ENABLE_LED_TEST
      // 更新LED状态
      if (new_state == GPIO_PIN_SET) {
          HAL_GPIO_WritePin(LED1_GPIO_Port, LED1_Pin, GPIO_PIN_SET);
      } else {
          HAL_GPIO_WritePin(LED1_GPIO_Port, LED1_Pin, GPIO_PIN_RESET);
      }
#endif
    }
  }
}
